#!/bin/bash
# Node.js 环境安装脚本

echo "=========================================="
echo "  📦 安装 Node.js 环境"
echo "=========================================="
echo ""

# 1. 安装 nvm
echo "步骤 1/3: 安装 nvm (Node Version Manager)..."
echo ""

if [ -d ~/.nvm ]; then
    echo "✅ nvm 已经安装"
else
    echo "📥 下载并安装 nvm..."
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
    
    if [ $? -eq 0 ]; then
        echo "✅ nvm 安装成功"
    else
        echo "❌ nvm 安装失败"
        exit 1
    fi
fi

echo ""
echo "步骤 2/3: 加载 nvm 环境..."

# 加载 nvm
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

if command -v nvm &> /dev/null; then
    echo "✅ nvm 加载成功"
    echo "   版本: $(nvm --version)"
else
    echo "⚠️  nvm 需要重新加载 shell"
    echo ""
    echo "请运行以下命令加载 nvm："
    echo "  source ~/.bashrc  # 或 source ~/.zshrc"
    echo ""
    echo "然后重新运行此脚本"
    exit 1
fi

echo ""
echo "步骤 3/3: 安装 Node.js LTS 版本..."

# 检查是否已安装
if command -v node &> /dev/null; then
    echo "✅ Node.js 已安装"
    echo "   版本: $(node --version)"
    echo "   npm版本: $(npm --version)"
else
    echo "📥 下载并安装 Node.js LTS..."
    nvm install --lts
    
    if [ $? -eq 0 ]; then
        echo "✅ Node.js 安装成功"
        echo "   版本: $(node --version)"
        echo "   npm版本: $(npm --version)"
    else
        echo "❌ Node.js 安装失败"
        exit 1
    fi
fi

echo ""
echo "=========================================="
echo "  ✅ Node.js 环境安装完成！"
echo "=========================================="
echo ""
echo "📝 环境信息："
echo "   Node.js: $(node --version)"
echo "   npm: $(npm --version)"
echo "   安装路径: $(which node)"
echo ""
echo "🎯 下一步："
echo "   1. 重新加载 shell（或打开新终端）"
echo "   2. 运行: cd /data/Matrix/yy/gjj_pre_merge-v1/frontend"
echo "   3. 运行: npm run dev -- --port 5174 --host 0.0.0.0"
echo ""
echo "或者直接运行："
echo "   bash 启动前端-完整版.sh"
echo ""
echo "=========================================="

